package com.GLM.Viewer.Users;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

public class UserFansActivity extends Activity{
	private final static int FRIENDLIST_LOADING = 111;
	private final static int FRIENDLIST_LONDED = 222;
	private ListView mFansList;
	private SimpleAdapter mFriendsAdapter;
	private List<Map<String, Object>> mFriendsItems = new ArrayList<Map<String, Object>>();
	private String[] friendsItemKeys = new String[] { "nickname", "loc" };
	private int[] friendsItemIds = new int[] { R.id.fans_nickname, R.id.fans_loc};
	private Map<String, String> friendsPics = new HashMap<String, String>();
	private int user_id;
	private int screenWidth;
	private int screenHeight;
	private ProgressBar mProgressBar;
	private AsynImageLoader imageLoader = new AsynImageLoader();
	
	private Map<Integer, Integer> FriendsMap = new HashMap<Integer, Integer>();
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case FRIENDLIST_LOADING:
				
				thread = new Thread(new Runnable() {
					public void run() {
						mProgressBar.setVisibility(View.VISIBLE);
						
						initFansList();
						mFriendsAdapter = new SimpleAdapter(UserFansActivity.this, mFriendsItems, R.layout.view_user_fans_item, friendsItemKeys, friendsItemIds);
						mHandler.sendEmptyMessage(FRIENDLIST_LONDED);
					}

				});
				thread.start();
				break;

			case FRIENDLIST_LONDED:
				mProgressBar.setVisibility(View.INVISIBLE);
				if (mFriendsAdapter != null && mFriendsItems.size() >0) {
					
					mFansList.setAdapter(mFriendsAdapter);
					bindItemClick();
				}else{
					Paint paint = new Paint();
					
					paint.setTextSize(20);
					paint.setAntiAlias(true);
					String str = getString(R.string.nofans);
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
					Canvas canvas = new Canvas(bitmap);
					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
					RelativeLayout layout = (RelativeLayout)findViewById(R.id.userfans_layout);
					Drawable drawable = new BitmapDrawable(bitmap);
					layout.setBackgroundDrawable(drawable);
				}
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_user_fans);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		mFansList = (ListView)findViewById(R.id.fans_listview);
		mProgressBar = (ProgressBar)findViewById(R.id.fans_list_progressbar);
		Intent intent = getIntent();
		user_id = intent.getIntExtra("user_id", -1);
		mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
	}

	public void bindItemClick(){
		mFansList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				int clickedUseId = FriendsMap.get(position);
				Intent intent = new Intent(UserFansActivity.this,UserInfoDetailActivity.class);
				intent.putExtra(Constant.INTENT_USER_ID, clickedUseId);
				startActivity(intent);
			}
		});
		
		mFansList.setOnScrollListener(scrollListener);
	}
	
	
	public OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
				LoadFriendPic();
		}
	};

	public void LoadFriendPic(){
		int count = mFansList.getChildCount();
		for (int i = 0; i < count; i++) {
			View view = mFansList.getChildAt(i);
			ImageView imageView = (ImageView) view.findViewById(R.id.fans_avatar);
			String key = String.valueOf(i);
			String picurl = friendsPics.get(key);

			if (picurl != null && picurl != "") {
				Log.d("friendsUrl", picurl);
				imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE + picurl, R.drawable.glm_white);

			}
		}
	}
	public void initFansList(){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_CLASSID, user_id );
			jsonData.put(Constant.PARAM_USERID_ONE, user_id);
			jsonData.put(Constant.PARAM_FRIENDS_CLASS, 3);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDSSMS, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_PARTY_USERS);

					initFriendItemFromJson(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}
	
	public void initFriendItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		
		for (int i = 0; i < jsonArray.length(); i++) {
			UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			
			item.put("nickname", entity.getUd_nickname());
			
			item.put("loc", entity.getLoc_name());
			mFriendsItems.add(item);
			Log.d("Loc_id>", entity.getUser_avatar() + "");
			friendsPics.put(String.valueOf(i), entity.getUser_avatar());
		    FriendsMap.put(i, entity.getUser_id());
		}
	}

	public void gobackbtn_OnClick(View v){
		NavUtils.navigateUpFromSameTask(UserFansActivity.this);
	}
}
